package api;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Proxy;
import java.net.InetAddress;
import java.net.Socket;

import rmi.InvokeRMI;

public class RMIClient   {
	
	
	public RMIClient(InetAddress adress, int port) {
		super();
		this.adress = adress;
		this.port = port;
	}

	InetAddress adress;
	int port;
	/**
	 * The stub to return
	 */
	private InvokeRMI stub;
	
	/**
	 * Constructor
	 * 
	 * @param adress
	 * @param port
	 */
	

	/**
	 * Return the stub
	 * 
	 * @return Object
	 */
	public Object getStub() {
		try {
			// Init the socket with writer and reader
			Socket socket = new Socket(this.adress.getHostAddress(), this.port);
			ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
			ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
			objOut.writeObject("i want a stub");
			
	        // Receive stub
			try {
				Object c  = objIn.readObject();
				//Proxy à 
				stub =(InvokeRMI)Proxy.newProxyInstance(
						InvokeRMI.class.getClassLoader(),
						new Class[] { InvokeRMI.class },
						new CustomHandler()
						);
				return this.stub;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return stub;
	}
	
	
}